package org.kolonitsky.alexey.net
{
    import flash.events.EventDispatcher;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.geom.Point;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    /**
     *  Complete event dispatched on file loading complete.
     */
    [Event(name="complete", type="flash.events.Event")]

    /**
     * Service for receive and pars RSS-information
     * Developer for TUT.BY
     * @author Alexey Kolonitsky
     * @date 25.05.2009
     */
    public class RSSService extends XMLService
    {
	
	/**
	 * @constructor
	 * @param uri of rss source file
	 */
	public function RSSService (): void 
	{
	    super("")
	    rootCloseNode = "</rss>"
	}

	
	/** 
	 * get RSS item by index.
	 * @param index of item in source file.
	 * @return object with next fields 
	 * <ul>
	 *   <li>title post title</li>
	 *   <li>link link to full post</li>
	 *   <li>description post desctioption</li>
	 *   <li>category post category</li>
	 *   <li>pubDate publish date</li>
	 *   <li>image image url</li>
	 *   <li>thumbnail URL of more compact thumbnail in item</li>
	 * </ul>
	 */
	public function getItem (index:uint):Object 
	{
	    var channelNode:XML = _data.channel[0]
	    var itemNode:XML = channelNode.item[index]
	    var item: Object = 
	    {
		title: String(itemNode.title),
		link: String(itemNode.link),
		description: String(itemNode.description),
		category: String(itemNode.category),
                pubDate: new Date(String(itemNode.pubDate))
	    };
	    
	    var imgNode: XML = itemNode..media::content[0];
	    if (imgNode)
	        item.image = String(imgNode.@url);

	    var thumbnailList:XMLList = itemNode..media::thumbnail;
	    var thumbnailURL:String = parsThumbnails(thumbnailList);
	    if (thumbnailURL)
	        item.thumbnail = String(thumbnailURL);
	    
	    return item
	}

	
	/** 
	 * Get all RSS items count
	 * @return count of posts in source rss file 
	 */
	public function get length (): int 
	{
	    var channelNode:XML = _data.channel[0]
	    var items:XMLList = channelNode.item
	    return items.length()
	}

	
	/**
	 *  Get URL of more compact thumbnail. If thumbnail is one
	 *  get it URL.
	 */
	private function parsThumbnails(thumbnailList:XMLList):String
	{
	    default xml namespace = media;

	    var resultNode:XML = null;
	    var minPoint:Point = null;
	    var point:Point = new Point();
	    for each(var thumbnailNode:XML in thumbnailList)
	    {
		point = new Point(thumbnailNode.@width, thumbnailNode.@height);
		
		if (minPoint == null || minPoint.length > point.length)
		{
		    minPoint = point.clone();
		    resultNode = thumbnailNode;
		}
	    }

	    return String(resultNode ? resultNode.@url : "");
	}
	
    }

}